<!DOCTYPE html>
<html lang="en" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body onload="disConnect()">
<div>
    <button type="button" id="connect" onclick="connect();">连接</button>
    <button type="button" id="disConnect" disabled="disabled" onclick="disConnect();">断开连接</button>
</div>

<div id="conversationDiv">
    <label>输入你的名字</label> <input type="text" id="name">
    <button type="button" id="sendName" onclick="sendName();">发送</button>
    <p id="response"></p>
</div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/stomp.js/2.3.3/stomp.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/sockjs-client/1.3.0/sockjs.min.js"></script>
<script th:src="@{/jquery.min.js}"></script>

<script>
    var stompClient = null;

    /* 初始化.*/
    function disConnect() {
        if (stompClient != null) {
            stompClient.disconnect();
        }
        setConnection(false);
        console.log("DisConnected")
    }

    /* 初始化详情. */
    function setConnection(connected) {
        document.getElementById('connect').disabled = connected;
        document.getElementById('disConnect').disabled = !connected;
        document.getElementById('conversationDiv').style.visibility = connected ? 'visible' : 'hidden';
        $('#response').html();
    }

    /* 连接 */
    function connect() {
        var socket = new SockJS('/endpointWisely');
        stompClient = Stomp.over(socket);
        stompClient.connect({}, function (frame) {
            setConnection(true);
            console.log("Connected：" + frame);
            stompClient.subscribe('/topic/getResponse', function (response) {
                showResponse(JSON.parse(response.body).responseMessage);
            });
        });
    }

    /* 发送消息 */
    function sendName() {
        var name = $('#name').val();
        stompClient.send("/welcome", {}, JSON.stringify({'name': name}));
    }

    /* 回显服务器响应消息. */
    function showResponse(message) {
        $('#response').html(message);
    }


</script>
</body>
</html>